package com.lagou.edu.mvcframework.servlet;

import com.lagou.edu.mvcframework.annotations.*;
import com.lagou.edu.mvcframework.pojo.Handle;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Auther: whh
 * @Date: 2021/3/30 0030
 * @Description:
 */
public class LgDispatcherServlet extends HttpServlet {


    private Properties properties = new Properties();

    //用于缓存扫描到的类的全限定类名
    private List<String> classNames = new ArrayList<>();

    //ioc容器
    private Map<String,Object> ioc = new HashMap<>();

    //handleMapping,存储url和method之间的映射关系
    //private Map<String,Method> handleMapping = new HashMap<>();
    private List<Handle> handleMapping = new ArrayList<>();


    @Override
    public void init(ServletConfig config) throws ServletException {
        //1 加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);

        //2 扫描相关的类，扫描注解
        doScan(properties.getProperty("scanPackage"));

        //3 初始化bean对象（实现ioc容器，基于注解）
        doInstance();

        //4 实现依赖注入
        doAutoWired();

        //5 构造一个handleMapper处理器映射器，将配置好的url和method建立映射关系
        initHandleMapping();


        System.out.println("springmvc初始化完成...");
        //等待请求进入,处理请求
    }

    //构造一个handleMapper处理器映射器
    //最关键的一步
    private void initHandleMapping() {
        if(ioc.isEmpty()) {return;}
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> aClass = entry.getValue().getClass();
            if(!aClass.isAnnotationPresent(LagouController.class)) {continue;}
            String baseUrl = "";
            if(aClass.isAnnotationPresent(LagouRequestMapping.class)){
                LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
                baseUrl = annotation.value();
            }
            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                if(!method.isAnnotationPresent(LagouRequestMapping.class)){continue;}

                LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
                String methodUrl = annotation.value();
                String url = baseUrl+methodUrl;

                List<String> userList = new ArrayList<>();
                // 若类上和方法上有同时有 @LagouSecurity 注解
                if (aClass.isAnnotationPresent(Security.class) && method.isAnnotationPresent(Security.class)) {
                    Security classAnnotation = aClass.getAnnotation(Security.class);
                    Security methodSecurity = method.getAnnotation(Security.class);
                    List<String> methodList = Arrays.asList(methodSecurity.value());
                    List<String> classList = Arrays.asList(classAnnotation.value());
                    //遍历方法的username集合 如果匹配则放入handle中
                    for (String name : methodList) {
                        if(classList.contains(name)){
                            userList.add(name);
                        }
                    }
                }

                //把method所有信息及url封装为一个handle
                Handle handle = new Handle(entry.getValue(),method, Pattern.compile(url),userList);

                //计算方法的参数位置
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    //对HttpServletRequest和HttpServletResponse进行特殊处理，将其类名保存在参数map中
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class){
                        handle.getParamIndexMapping().put(parameter.getType().getSimpleName(),i);
                    }else{
                        handle.getParamIndexMapping().put(parameter.getName(),i);
                    }
                }
                //建立url和method的映射关系
                handleMapping.add(handle);
            }

        }

    }

    //实现依赖注入
    private void doAutoWired() {
        if(ioc.isEmpty()) return;

        //有对象，再进行依赖注入处理

        //遍历ioc中的所有对象，查看对象中的字段，是否有@LagouAutowired注解，有则需要维护依赖注入
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取bean对象中的字段信息
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            //遍历处理
            for (Field declaredField : declaredFields) {
                if(!declaredField.isAnnotationPresent(LagouAutowired.class)) continue;
                //有该注解
                LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.class);
                String beanName = annotation.value();
                if("".equals(beanName)){
                    ///没有配置具体的beanid，那就需要根据当前字段类型注入（接口注入）
                    beanName = declaredField.getType().getName();
                }
                //开启赋值
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }


    }

    //ioc容器
    //基于classNames缓存的类的全限定类名，以及反射技术，完成对象的创建和管理
    private void doInstance() {

        if(classNames.size()==0) return;

        try {
            for (String className : classNames) {
                //反射
                Class<?> aClass = Class.forName(className);
                //区分controller和service
                if(aClass.isAnnotationPresent(LagouController.class)){
                    //controller的id此处不过多处理，就拿类的首字母小写作为id，保存在ioc中
                    String simpleName = aClass.getSimpleName();
                    String lowerFirstSimpleName = lowerFirst(simpleName);
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstSimpleName,o);
                }else if(aClass.isAnnotationPresent(LagouService.class)){
                    LagouService annotation = aClass.getAnnotation(LagouService.class);
                    //获取注解value值
                    String beanName = annotation.value();
                    //如果指定了id，就以指定的为准
                    if(!"".equals(beanName)){
                        ioc.put(beanName,aClass.newInstance());
                    }else {
                        beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName,aClass.newInstance());
                    }

                    //service层往往有接口的，面向接口开发，按接口名放入ioc，便于后期根据接口类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> anInterface : interfaces) {
                        ioc.put(anInterface.getName(),aClass.newInstance());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }



    }

    private String lowerFirst(String str){
        char[] chars = str.toCharArray();
        if('A' <= chars[0] && chars[0] <= 'Z'){
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    //扫描类
    //scanPackage:com.lagou.demo
    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");

        File pack = new File(scanPackagePath);

        File[] files = pack.listFiles();

        for (File file : files) {
            if(file.isDirectory()){ //子package
                //递归
                doScan(scanPackage+"."+file.getName());
            }else if (file.getName().endsWith(".class")){
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }
    }

    //加载配置文件
    private void doLoadConfig(String contextConfigLocation) {

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);

        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求

        //根据url获取到能够处理当前请求的handler
        Handle handle = getHandle(req);

        if(handle == null){
            resp.getWriter().write("404 not found");
            return;
        }

        //进行参数绑定
        //获取所有参数类型的数组，这个数组的长度就是要传入的args的长度
        Class<?>[] parameterTypes = handle.getMethod().getParameterTypes();

        //根据上述的数组长度创建一个新的参数数组，是要传入反射用的（args）
        Object[] paramValues = new Object[parameterTypes.length];

        //以下就是为了向参数数组中塞值，而且保证顺序一致
        Map<String,String[]> parameterMap = req.getParameterMap();

        String userName = "";

        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {

            //name=1&name=2 -> 1,2
            String value = StringUtils.join(param.getValue(), ",");

            if("username".equals(param.getKey())){
                userName = StringUtils.join(param.getValue(), ",");
            }

            //如果参数和方法中的参数匹配上了，则填充数据
            if(!handle.getParamIndexMapping().containsKey(param.getKey())){continue;}

            Integer index = handle.getParamIndexMapping().get(param.getKey());

            paramValues[index] = value;

        }

        Integer requestIndex = handle.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paramValues[requestIndex] = req;

        Integer responseIndex = handle.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paramValues[responseIndex] = resp;

        try {
            resp.setContentType("text/html; charset=utf-8");
            //判断请求参数中是否有username参数的值
            if(!StringUtils.isEmpty(userName)){
                //判断handle中的username集合是否包含该请求中username的值
                if(!handle.getUsers().contains(userName)){
                    resp.getWriter().write("未授权访问！");
                }else{
                    handle.getMethod().invoke(handle.getController(),paramValues);
                }
            }else{
                resp.getWriter().write("未授权访问！");
            }

        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    private Handle getHandle(HttpServletRequest req) {
        if(handleMapping.isEmpty()){return null;}

        String requestURI = req.getRequestURI();

        for (Handle handle : handleMapping) {
            Matcher matcher = handle.getPattern().matcher(requestURI);
            if(!matcher.matches()){continue;}
            return handle;
        }
        return null;
    }
}
